from pymongo import MongoClient

import config
import reslutJson


def checkCon(func):
    def wrapper(instance, *args, **kwargs):
        try:
            instance.checkClient()
            return func(instance, *args, **kwargs)
        except Exception as e:
            print(e)
    return wrapper


class mongo(object):
    client = None
    site = None

    def __init__(self):
        self.checkClient()
    # 获取连接

    def checkClient(self):
        try:
            if self.client is None or self.site is None:
                self.client = MongoClient(
                    config.mongo_host, username=config.mongo_username, password=config.mongo_password)
                self.site = self.client[config.mongo_dbname]
        except Exception as e:
            print(e)

    # 保存爬虫分析数据
    @checkCon
    def spider2DB(self, data):
        try:
            tree = data["tree"]
            bar = data["bar"]
            pie = data["pie"]
            self.site["tree"].insert(tree)
            self.site["bar"].insert(bar)
            self.site["pie"].insert(pie)
        except Exception as e:
            print(e)
    # 检查文档是否存在

    @checkCon
    def checkinDB(self, gtype=None, domains=None):
        print(gtype, domains)
        if gtype and domains:
            try:
                x = self.getDict(gtype, domains)
                # print(x)
                # if len(x):
                #     return 200  # "数据库查询到该数据"
                # else:
                #     return 204  # 数据库无数据
                return len(x)
            except Exception as e:
                print(e)
                return -1  # "数据库查询异常"

    # 获取文档
    @checkCon
    def getDict(self, gtype=None, domains=None):
        if gtype and domains:
            x = []
            try:
                docs = self.site[gtype]
                Fields = {"_id": False}
                items = docs.find({"url": domains}, projection=Fields)
                for item in items:
                    x.append(item)
            except Exception as e:
                print(e)
                # return []
            return x

    # 获取所有集合名
    @checkCon
    def allcollections(self):
        return self.site.collection_names()

    # suffix_url为None代表删除所有 不对外开放
    # 删除集合,suffix_url代表只删除一种后缀的集合 pie_... tree_... bar_...
    @checkCon
    def dropcollections(self, suffix_url=None):
        coll = self.allcollections()
        try:
            deled = 0
            for s in coll:
                if suffix_url is None:
                    self.site[s].drop()
                else:
                    index = s.find(suffix_url)
                    if index > 0:
                        self.site[s].drop()
                        deled = deled + 1
                if deled >= 3:
                    break
            return True
        except Exception as e:
            print(e)
            return False
